<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>批量运行日志</title>
  <style>
    body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, "PingFang SC", "Microsoft Yahei", sans-serif; margin: 1rem; }
    .wrap { max-width: 1100px; margin: 0 auto; }
    .head { display:flex; align-items:center; justify-content:space-between; margin: .5rem 0 1rem; }
    .kb { background:#eef2ff; border:1px solid #c7d2fe; padding:.5rem .75rem; border-radius:.25rem; font-size:.9rem; }
    pre { background: #0b1020; color: #d1d5db; padding: 1rem; border-radius: .5rem; overflow:auto; max-height: 70vh; white-space: pre-wrap; }
    a { color: #4f46e5; text-decoration: none; }
    .muted { color: #666; font-size:.9rem; }
  </style>
</head>
<body>
  <div class="wrap">
    <div class="head">
      <div>
        <h2 style="margin:.25rem 0;">批量流水线运行中...</h2>
        <div class="muted">任务ID：<code>{{ task_id }}</code>，总数：{{ count }}</div>
      </div>
      <div><a href="/" class="kb">返回</a></div>
    </div>

    <div class="muted" style="margin:.5rem 0;">
      当前主题：<code id="curTheme">(等待...)</code>
      &nbsp;&nbsp;|&nbsp;&nbsp;
      当前Query：<code id="curQuery">(等待...)</code>
    </div>
    <pre id="log"></pre>
    <div id="status" class="muted">状态：<span id="stat">连接中...</span></div>
  </div>

  <script>
    const logEl = document.getElementById('log');
    const statEl = document.getElementById('stat');
    const taskId = "{{ task_id }}";
    const es = new EventSource('/stream-batch?task_id=' + encodeURIComponent(taskId));
    function append(line) {
      logEl.textContent += line + "\n";
      logEl.scrollTop = logEl.scrollHeight;
    }
    es.onmessage = (ev) => {
      if (!ev || typeof ev.data !== 'string') return;
      append(ev.data);
      // update current THEME/QUERY from task lines
      if (ev.data.startsWith('TASK ') && ev.data.includes(' THEME: ')) {
        const idx = ev.data.indexOf(' THEME: ');
        const theme = ev.data.substring(idx + 8);
        document.getElementById('curTheme').textContent = theme;
      }
      if (ev.data.startsWith('TASK ') && ev.data.includes(' QUERY: ')) {
        const idx = ev.data.indexOf(' QUERY: ');
        const query = ev.data.substring(idx + 8);
        document.getElementById('curQuery').textContent = query;
      }
      if (ev.data.startsWith('BATCH EXIT')) {
        statEl.textContent = '完成';
        es.close();
      }
      if (ev.data.startsWith('ERROR:') || ev.data.startsWith('TASK ERROR')) {
        statEl.textContent = '发生错误';
      }
    };
    es.onerror = (e) => {
      statEl.textContent = '连接断开或发生错误';
    };
  </script>
</body>
</html>
